<?php namespace Wdl\helper;

class FrontHelper{

  public static function check_login()
  {
    $ret =  self::get_broker();
    if(!$ret || empty($ret['mobile'])){
        exit(json_encode(array(
          'errno' => 401,
          'message' => '需要登录',
          'data' => $ret,
        )));
    }
  }
  /** 
    * 获取指定条数的通知
    */
   public  static   function get_notice_list($limit = 3){
       global $_W;
       $list = pdo_fetchall("select * from ".tablename("kbwdl_saleinfo").
           " where tid=10 and fid=:fid and uniacid=:uniacid order by orderid desc limit $limit",
           ['fid'=> 0, 'uniacid'=> webHelper::bindUniacid()]);
       
       return $list;
   }

   public static function get_broker( $bid =0, $by_openid = false  )
   {
     global $_W, $_GPC;
     if($bid){
        if($by_openid){

          $ret = pdo_fetch("select * from ".tablename("kbwdl_broker")
          ." where uniacid=:uniacid AND openid=:openid", 
          ['uniacid'=> webHelper::bindUniacid(),'openid'=> $bid]);

        }else if(is_numeric($bid)){
          $ret = pdo_fetch("select * from ".tablename("kbwdl_broker")
              ." where uniacid=:uniacid AND id=:id", 
              ['uniacid'=> webHelper::bindUniacid(),'id'=> $bid]);
        }else{
          $ret = pdo_fetch("select * from ".tablename("kbwdl_broker")
            ." where uniacid=:uniacid AND openid=:openid", 
            ['uniacid'=> webHelper::bindUniacid(),'openid'=> $bid]);

        }
     
     }else{
       
      $openid = !empty($_W['openid']) ?$_W['openid']: (isset($_GPC['openid']) ? $_GPC['openid'] :'');
 
      $ret = pdo_fetch("select * from ".tablename("kbwdl_broker")
             ." where uniacid=:uniacid AND openid=:openid", 
             ['uniacid'=> webHelper::bindUniacid(),'openid'=> $openid]);
       
     }
      if($ret && $ret['mobile']) {
          $ret['avatar'] = tomedia($ret['avatar']);
          $ret['mobile_label'] = substr($ret['mobile'],0,3) ."******".substr($ret['mobile'],-2);
          pdo_update("kbwdl_broker",['updated_time'=> TIMESTAMP], ['id'=> $ret['id']]);
      }
     
      return $ret;
   }

   /**
    * 获取区域和商圈的二维数组给小程序
    */
   public static function get_areas_quan($areas)
   {
      global $_W;
      if(!is_array($areas)){
        $areas = form_element::_option( $areas);
      }
      
      
      $quans = pdo_fetchall("select * from" .tablename("kbwdl_area"). 
            " WHERE uniacid=:uniacid and type=2 and disabled=0 order by orderid desc",
          [ 'uniacid'=> webHelper::bindUniacid() ]);
      $arrs = [];
      foreach($quans as $item){
        $arrs[ $item['area']][] = [
            'title' => $item['name'],
            'id' => $item['id'],
            'color'=> '#fff',
            'children'=>[],
        ];
      }
      $i = 1;
      $data = [];
      foreach($areas as $key =>  $item){
       $data[] =  [
                  'title' => $item ,
                  'id' =>  1000000000+ $i,
                  'color'=> '#fff',
                  'children'=> isset($arrs[$key]) ? $arrs[$key] :[],
              ];
        $i++;
      }

      return $data;
   }
   public static function chuzu_tags( $disposition )
   {
      $selects = webHelper::sechouse_form_data();
      $type = [
        'rent_zhu'=> '环 境',
        'rent_zhu_all' => '配 套',
        'rent_zhu_mensuo'=> '门 锁',
        'rent_zhu_chufang'=> '厨 房',
        'rent_zhu_keting'=> '客 厅',
        'rent_zhu_weishengjian'=> '卫生间',
        'rent_zhu_woshi'=> '卧 室',
      ];
      foreach($type as $field => $name){
        $rent_zhu = explode(",", $selects[ $field ]);
        $tag[ $field ]['name'] =  $name ;
        foreach($rent_zhu as  $t){
          if(strpos($disposition, $t) !== false){
            $tag[ $field]['tags'][] = $t;
          }
        }
      }
   
      
      
      return $tag;
   }

   public static function getNewsDetail($id, $uniacid)
   {
       /* 分类统计 */ 
        $ret  = pdo_fetch("select * from ".tablename("kbwdl_saleinfo")." where uniacid='$uniacid'  and disabled=0 and id='$id'");
        if(empty($ret)){
            return  false;
        }
        $ret['newstext'] = htmlspecialchars_decode($ret['newstext']);
            
            /* 处理房源信息 获取腾讯实际播放地址 */
        preg_match('/<iframe(.*?)src="(.*?)"/', $ret['newstext'], $arr);
        $ret['vurl'] = $arr[2];
        $urlinfo = parse_url($arr[2]);
        if(!empty($urlinfo['query'])){
            $query = explode('&', $urlinfo['query']);
            $a2 = array();
                foreach ($query as $q)
                {
                    $a1 = explode('=', $q);
                    $a2[$a1[0]] = $a1[1];
                }
        }
        $ret['videoid'] = $a2['vid'];
        $furl_real = '';
        if(!empty($ret['videoid'])){
          // echo  $a3 = file_get_contents('http://vv.video.qq.com/getinfo?vids='.$info['videoid'].'&platform=101001&charge=0&otype=json');
          $a3 = file_get_contents('https://vv.video.qq.com/getinfo?otype=json&appver=3.2.19.333&platform=11&defnpayver=1&vid='.$ret['videoid']);
            $a3  = str_replace('QZOutputJson=', '', rtrim($a3,';'));
            $a3 = json_decode($a3, true);
          
            $fvkey = $a3['vl']['vi'][0]['fvkey'];
            $fn = $a3['vl']['vi'][0]['fn'];
            $furl = $a3['vl']['vi'][0]['ul']['ui'][0]['url'];
            $furl_real = $furl .$fn .'?vkey='.$fvkey;
        }
        $ret['videoinfo'] = $furl_real;
        /* 结束腾讯视频获取 */
        $ret['thumb'] = tomedia($ret['thumb']);
        /*获取自己上传的视频*/
        if(!empty($ret['video']) && strpos($ret['video'],'mages')){
            $ret['video'] = tomedia($ret['video']);           
        }else{
            /*获取后台插入的视频*/
            preg_match('/<video(.*?)src="(.*?)"/', $ret['newstext'], $arr);
            $ret['video'] = $arr[2];
        } 
        /*获取全部图片*/
        $pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.bmp|\.png]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$ret['newstext'],$match);
        $ret['allpics'] = $match[1]; 
        $ret['gpoun_num'] = $ret['gpoun_num']==1?1:0;
        /*更新浏览*/
        $ret['onclick'] = $ret['onclick']+1;
        pdo_update('kbwdl_saleinfo', array('onclick'=> $ret['onclick'] ), array('id'=> $id));
        return $ret;
    }
    static public function checkIsMobile($mobile) {
        if (!is_numeric($mobile)) {
          return false;
        }
        return preg_match('/^1[2345789]\d{9}$/', $mobile) ? true : false;
    }
    /**
     * 
     * 小程序安全检查
     * @param mixed $data
     * @return bool
     */
    static public function checkPostContent($data)
    {
        global $_W ;
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= :acid",['acid'=> $_W['uniacid']] );  
        if(! $account ){
          return true;
        }
        /*鉴别内容*/
        $config = webHelper::fetch_place_data('setting', 'security');
        /*关闭时不用*/
        if(isset($config['closecheck']) &&  $config['closecheck']==1){
          return true;
        }
        $str = implode("", $data);
        load()->func('communication');     
        /*获取小程序access_token*/
        load()->classs('wxapp.account');          
             
        $accObj= new \WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );  
        $WxApi = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={$ACCESS_TOKEN}";
        /*JSON_UNESCAPED_UNICODE 确保json数据不被编码*/
        $ret = ihttp_post($WxApi,  json_encode(array('content'=>$str ),JSON_UNESCAPED_UNICODE));
        if($ret['content']){
          $ret = json_decode( $ret['content'], true);
          
          if(isset($ret['errcode']) && $ret['errcode'] &&  $ret['errcode'] == 87014 ){
               return false;
          }
        } 
        
        return true;
        
    }
}